/*
 * Copyright (C) 2009 Jakub Miara
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.araim.rringtone;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ToggleButton;

import com.araim.rringtone.db.RandomRingtoneDatabase;

/**
 * 
 * @author Jakub Miara
 * @version 1.0
 * 
 *          Main Activity of Random Ringtone Application - basically it's a
 *          preferences screen. Allows for turning on/off and moving to ringtone
 *          selection
 * 
 */
public class RandomRingtone extends Activity {

	/**
	 * shared preferences key - random ringtone is on/off
	 */
	public static final String RRINGTONE_ACTIVE = "RRINGTONE_ACTIVE";
	public static final String NOTIFICATION_ACTIVE = "NOTIFICATION_ACTIVE";
	
	/**
	 * Shared preferences name
	 */
	public static final String RRINGTONE_PREFS_NAME = "araim.rringtone.preferences";
	public static final String ENABLED_ALARMS = "araim.rringtone.alarms.preferences";
	public static final String ORIGINAL_ALARMS = "araim.rringtone.alarms.restore";
	
	/**
	 * log tag
	 */
	public static final String TAG = "RingtoneChange";

	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		findViewById(R.id.ringtonesButton).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Log.d(TAG, "Starting ringtone selection");
				// create new intent to display ringtone selection activity

				Intent i = new Intent(getApplicationContext(), SelectRingtonesActivity.class);
				i.putExtra(SelectRingtonesActivity.RINGTONE_TYPE, RingtoneManager.TYPE_RINGTONE);
				startActivityForResult(i, 1);
			}
		});

		findViewById(R.id.notificationsButton).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Log.d(TAG, "Starting notification selection");
				// create new intent to display ringtone selection activity

				Intent i = new Intent(getApplicationContext(), SelectRingtonesActivity.class);
				i.putExtra(SelectRingtonesActivity.RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
				startActivityForResult(i, 1);
			}
		});
		
		
		findViewById(R.id.alarmsButton).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Log.d(TAG, "Starting alarm selection");
				Intent i = new Intent(getApplicationContext(), ListAlarmsActivity.class);
				startActivity(i);
				/*
				Uri u = Uri.parse("content://com.android.alarmclock/alarm");
				
				Cursor c = getContentResolver().query(u, new String[]{"_ID","message","alert"}, null, null, null);
				while(c.moveToNext()){
					Log.d(TAG, "Alarm found: " + c.getInt(0) + " : " + c.getString(1) + " : " + c.getString(2));
				}
				c.close();
				ContentValues cv = new ContentValues();
				cv.put("alert", "content://media/internal/audio/media/37");
				Uri u2 = Uri.parse("content://com.android.alarmclock/alarm/3");
				getContentResolver().update(u2, cv, "ID = ?", new String[]{"3"});*/
				
/*
				// create new intent to display ringtone selection activity
				Intent i = new Intent(getApplicationContext(), SelectRingtonesActivity.class);
				i.putExtra(SelectRingtonesActivity.RINGTONE_TYPE, RingtoneManager.TYPE_ALARM);
				startActivityForResult(i, 1);
	*/			
			}
		});

		ToggleButton tb = (ToggleButton) findViewById(R.id.ringtone_onoff);
		SharedPreferences settings = RandomRingtone.this.getSharedPreferences(RRINGTONE_PREFS_NAME, 0);

		tb.setChecked(settings.getBoolean(RRINGTONE_ACTIVE, false));
		tb.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				try {
					ToggleButton tb = (ToggleButton) v;

					Log.d(TAG, "Random ringtone turned " + (tb.isChecked() ? "on" : "off"));
					// whether the ringtone changing is on or off is stored in
					// shared preferences
					SharedPreferences settings = RandomRingtone.this.getSharedPreferences(RRINGTONE_PREFS_NAME, 0);

					SharedPreferences.Editor edtr = settings.edit();
					edtr.putBoolean(RRINGTONE_ACTIVE, tb.isChecked());
					edtr.commit();
				} catch (Exception e) {
					Log.e(TAG, "Error turning the Random Ringtone on/off" + e.toString());
				}
			}
		});
		
		tb = (ToggleButton) findViewById(R.id.notification_onoff);
		tb.setChecked(settings.getBoolean(NOTIFICATION_ACTIVE, false));
		tb.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				try {
					ToggleButton tb = (ToggleButton) v;

					Log.d(TAG, "Random notification turned " + (tb.isChecked() ? "on" : "off"));
					SharedPreferences settings = RandomRingtone.this.getSharedPreferences(RRINGTONE_PREFS_NAME, 0);

					SharedPreferences.Editor edtr = settings.edit();
					edtr.putBoolean(NOTIFICATION_ACTIVE, tb.isChecked());
					edtr.commit();
				} catch (Exception e) {
					Log.e(TAG, "Error turning the Random Notification on/off" + e.toString());
				}
			}
		});


		findViewById(R.id.smsHelpButton).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				View w = LayoutInflater.from(getApplicationContext()).inflate(R.layout.smsmessage, null);
				new AlertDialog.Builder(RandomRingtone.this).setTitle("Text message notifications").setView(w)
						.setPositiveButton("OK", null).show();
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		try {
			// we only start one activity, so this is the return from ringtone
			// selection
			// if user pressed SAVE (result is OK)
			if (data != null && resultCode == RESULT_OK) {
				// get the list of the ringtones
				Parcelable[] rings = data.getParcelableArrayExtra(SelectRingtonesActivity.SAVED_RINGTONES_LIST);
				int type = data.getIntExtra(SelectRingtonesActivity.RINGTONE_TYPE, -1);
				if (type != -1) {
					RandomRingtoneDatabase rrd = new RandomRingtoneDatabase(getApplicationContext());
					// if any was selected
					if (rings != null) {
						Log.i(TAG, "User selected " + rings.length + " ringtones");
						// clear the database
						rrd.clear(type);
						// insert each ringtone
						for (Parcelable p : rings) {
							RingtoneInfo ri = (RingtoneInfo) p;
							rrd.insertRingtone(ri);
						}
						// none was selected
					} else {
						rrd.clear(type);
					}
				}
			}
		} catch (Exception e) {
			Log.e(TAG, "Error on returning from ringtone selection requestcode: " + requestCode + " resultcode: " + resultCode);
			Log.e(TAG, "Error on returning from ringtone selection:" + e.toString());
		}
	}
}